<template>
  <div>
    <el-upload
      :action="FileUrl"
      ref="eluploadimg"
      :show-file-list="false"
      list-type="picture-card"
      :data="Data"
      :multiple="isMultiple"
      :headers="httpHeaders"
      :auto-upload="isAutoUpload"
      :on-success="handleAvatarSuccess"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-change="handleChange"
      :before-upload="beforeAvatarUpload"
      :on-progress="handleProgress"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
export default {
  name: "ImageUpload",
  props: {
    Data: {
      type: Object
    },
    FileUrl: {
      type: String
    },
    handleAvatarSuccess: {
      type: Function
    },
    beforeRemove: {
      type: Function
    },
    handleRemove: {
      type: Function
    },
    handleChange: {
      type: Function
    },
    handleProgress: {
      type: Function
    },

    imageUrl:{
        type:String,
        default:''
    },
    isMultiple:{
       type:Boolean,
       default:false
    },
    isAutoUpload:{
       type:Boolean,
       default:false
    }
  },

  data() {
    return {
      httpHeaders: {
        Authorization: getToken()
      },
      dialogImageUrl: "",
      dialogVisible: false
    };
  },
  methods: {
    // 上传前图片校验
    beforeAvatarUpload(file) {
      const isImage = file.type == "image/png" || file.type == "image/jpg" || file.type == "image/jpeg";
      if (!isImage) {
        this.$message.error("上传图片只能是JPG或者png格式!");
      }

      return isImage;
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 上传图片
    UploadSubmit() {
      this.$refs.eluploadimg.submit();
    },
    // 清除图片
    clearFiles() {
      this.$refs.eluploadimg.clearFiles();
    }
  }
};
</script>

<style lang="scss" scoped>
.avatar {
  width: 146px;
  height: 146px;
  display: block;
}
</style>


